package com.guoguo.api;

import com.alibaba.fastjson.JSONObject;
import com.guoguo.base.BaseController;

import com.guoguo.base.PageBean;
import com.guoguo.entity.UserExt;
import com.guoguo.entity.Users;


import com.guoguo.entity.vo.BuyAlbumVO;
import com.guoguo.entity.vo.UserInfoVO;
import com.guoguo.entity.vo.UsersVO;
import com.guoguo.entity.vo.UserFavouriteVO;
import com.guoguo.enums.AliOssImageEnum;
import com.guoguo.enums.UsersEnum;
import com.guoguo.service.*;
import com.guoguo.utils.*;
import com.guoguo.utils.aliOss.AliOssImageConfig;
import org.apache.log4j.spi.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.logging.Logger;

/**
 * Created by Administrator on 2017/8/8 0008.
 */
@RestController
@RequestMapping("/api/user")
public class UsersController extends BaseController {
    private final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(UsersController.class);

    @Resource
    private IUsersService usersService;

    @Resource
    private IUserExtService userExtService;
    @Resource
    private UserFavouriteService userFavouriteService;
    @Resource
    private BuyAlbumService buyAlbumService;

    @Resource
    private UploadService uploadService;

    /**
     * 查询用户信息
     *
     * @param userId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/findUser", method = RequestMethod.POST)
    public JSONObject findUser(HttpServletRequest request, @RequestParam String userId) {
        HttpSession session = request.getSession();
        logger.info("====================>>>>>>>>>>>     session id = " + session.getId());
        UserInfoVO userInfoVO = (UserInfoVO) session.getAttribute(userId);
        if (userInfoVO == null) {
            userInfoVO = this.usersService.findUsersInfoVO(userId);
            session.setAttribute(userId, userInfoVO);
        }
        logger.info("==============>>>>>>>>>>>      findUser   user Id = " + userInfoVO.getUserId() + "     icon url = " + userInfoVO.getIcon());
        return returnResult(200, userInfoVO, "");
    }

    /**
     * 修改用户信息
     *
     * @param userId
     * @param nickName
     * @param sex
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateUser", method = RequestMethod.POST)
    public JSONObject updateUserInfo(HttpServletRequest request, @RequestParam String userId, @RequestParam String nickName, @RequestParam int sex) {
        HttpSession session = request.getSession();
        logger.info("====================>>>>>>>>>>>     session id = " + session.getId());
        Users users = null;
        UserExt userExt = null;
        try {
            //
            nickName = new String(nickName.getBytes("iso-8859-1"), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (userId != null && !"".equals(userId)) {
            users = usersService.findUserById(userId);
            users.setNickname(nickName);
        }
        if (userId != null && !"".equals(userId)) {
            userExt = userExtService.findUserExt(userId);
            userExt.setSex(sex == 1 ? true : false);
            //修改用户时，icon连接会变，将icon置为null临时解决
            userExt.setIcon(null);
        }

        usersService.updateUsersInfo(users, userExt);

        UserInfoVO userInfoVO = this.usersService.findUsersInfoVO(userId);
        session.setAttribute(userId, userInfoVO);

        logger.info("==============>>>>>>>>>>>      updateUser   user Id = " + userInfoVO.getUserId() + "     icon url = " + userInfoVO.getIcon());

        return returnResult(200, new JSONObject(), "");
    }

    /**
     * 我喜欢的图片专辑
     *
     * @param userId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/Userfavourite", method = RequestMethod.POST)
    public JSONObject Userfavourite(@RequestParam String userId) {

        PageBean<UserFavouriteVO> userFavouritelist = userFavouriteService.Userfavourite(userId);
        return returnResult(200, userFavouritelist, "");
    }

    /**
     * 已购买的专辑详情
     *
     * @param userId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/UserBuyAlbum", method = RequestMethod.POST)
    public JSONObject UserBuyAlbum(@RequestParam String userId, int pageNum, int pageSize) {
        Map<String, Object> data = new HashMap();
        if (pageNum > 0 && pageSize < 20) {
            PageBean<BuyAlbumVO> BuyAlbumVOs = buyAlbumService.UserBuyAlbum(userId, pageNum, pageSize);
            return returnResult(200, BuyAlbumVOs, "");
        } else {
            return returnResult(UsersEnum.PAGE_PARAM_ERROR.getId(), data, UsersEnum.PAGE_PARAM_ERROR.getValue());
        }


    }


    /**
     * 头像上传
     *
     * @param fileName
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/uploadIcon", method = RequestMethod.POST)
    public JSONObject uploadFile(HttpServletRequest request, @RequestParam(value = "file", required = false) MultipartFile fileName, @RequestParam String userId) {
        HttpSession session = request.getSession();

        List<String> list = FileUtils.springFileUpload(request, 1);
        List<String> ossFile = uploadService.uploadFile(list);

        JSONObject jsonObject = new JSONObject();
//        AliOssImageConfig aliOssImageConfig = new AliOssImageConfig("test");

        if (ossFile.size() > 0) {
            jsonObject.put("icon", AliOssUtils.getImageUrl(ossFile.get(0)));//, aliOssImageConfig));
            userId = StringUtils.replace(userId, "\"", "");
            logger.debug("=======>>>   userId:" + userId);
            UserExt userExt = userExtService.findUserExt(userId);
            logger.debug("=======>>>   ossFile path:" + ossFile.get(0));
            logger.debug("==========>>>>>>>    userext is:" + userExt.getUserId());
            userExt.setIcon(ossFile.get(0));
            userExt.setUpdateTime(new Date());
            userExtService.updateUserExt(userExt);
        }
        //更新用户信息缓存
        UserInfoVO userInfoVO = this.usersService.findUsersInfoVO(userId);
        session.setAttribute(userId, userInfoVO);
        logger.info("====================>>>>>>>>>>>     session id = " + session.getId());
        logger.info("==============>>>>>>>>>>>      uploadIcon   user Id = " + userInfoVO.getUserId() + "     icon url = " + userInfoVO.getIcon());

        return returnResult(200, jsonObject, "");
    }


}

